package com.mzlalal.mybatis.interceptor.util;

import cn.hutool.core.lang.Assert;
import com.mzlalal.mybatis.interceptor.prop.MyBatisPlusProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * 获取tenantId工具
 *
 * @author Mzlalal
 * @date 2021/6/14 20:57
 **/
@Component
public class TenantIdService {
    private final MyBatisPlusProperties myBatisPlusProperties;

    @Autowired
    public TenantIdService(MyBatisPlusProperties myBatisPlusProperties) {
        this.myBatisPlusProperties = myBatisPlusProperties;
    }

    public String getCurrentReqTenantId() {
        // 判断是否有request
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        Assert.notNull(attributes, "my-tenant-starter:当前请求不是Web请求,无法获取Request对象,请使用MyBatisPlus忽略拦截器注解@InterceptorIgnore(tenantLine = \"true\")");

        // 租户ID名
        String tenantIdName = myBatisPlusProperties.getTenantIdName();

        // 从request获取租户ID
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        Object result = requestAttributes.getAttribute(tenantIdName, RequestAttributes.SCOPE_REQUEST);
        if (result == null) {
            // 为空,从session中尝试获取租户ID
            result = requestAttributes.getAttribute(tenantIdName, RequestAttributes.SCOPE_SESSION);
        }
        if (result == null) {
            return myBatisPlusProperties.getDefaultTenantId();
        }
        return (String) result;
    }
}
